import { Observable, Subject,share  } from 'rxjs'

// const observable = new Observable(subscriber => {
//   subscriber.next('observable execute');
//   setTimeout(() => {
//     subscriber.complete();
//   }, 1000);
// });
 

// const observer = {
//   next(x: any) { console.log('got value ' + x); },
//   error(err: any) { console.error('something wrong occurred: ' + err); },
//   complete() { console.log('done'); }
// }
// console.log('======just before subscribe');
// observable.subscribe(observer);
// console.log('======just after subscribe');


// const source$ = new Observable(subscriber => {
//   console.log('stream 开始');
//   subscriber.next(1);
//   subscriber.next(2);
//   subscriber.next(3);
//   subscriber.next(4);
//   console.log('steam 结束');
//   subscriber.complete();
// });
 
// source$.subscribe(data => console.log(`Observable 第一次订阅: ${data}`));
// // 1, 2, 3, 4
// source$.subscribe(data => console.log(`Observable 第二次订阅: ${data}`));
// // 1, 2, 3, 4



// const source$ = new Subject();

// source$.subscribe(data => console.log(`Subject 第一次订阅: ${data}`));
// // 1, 2, 3, 4
  
// source$.next(1);
// source$.next(2);

// source$.subscribe(data => console.log(`Subject 第二次订阅: ${data}`));
// // 3, 4

// source$.next(3);
// source$.next(4);

// source$.subscribe(data => console.log(`Subject 第三次订阅: ${data}`));
// // (沒收到任何事件就结束了)
// source$.complete();

const source$ = new Observable(observe => {
  console.log('stream 开始');
  setTimeout(() => observe.next(1), 100);
  setTimeout(() => observe.next(2), 200);
  setTimeout(() => observe.next(3), 300);
  setTimeout(() => {
      observe.next(4);
      observe.complete();
    console.log('stream 结束');
  }, 400);
});

const hotSource$ = source$.pipe(
  share()
);

setTimeout(() => {
  hotSource$.subscribe(data => console.log(`Observable 第一次订阅： ${data}`));

  setTimeout(() => {
    hotSource$.subscribe(data => console.log(`Observable 第二次订阅：${data}`));
  }, 200);
}, 1000);